
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components'
import { serverHost, showToast, uploadPath, getToken } from '../utils/common'

import './imgUpload.scss'

import bg_04 from './static/bg_04.png'

/**
 *
 */
export default class ImgUpload extends Component {
  constructor() {
    super(...arguments)
  }

  state = {
    imgUpload: '',
  }

  componentWillMount() {}

  config: Config = {
    navigationBarTitleText: '文件上传'
  }

  // 图片上传
  imgUpload = () => {
    Taro.chooseImage({
      sourceType: ['album', 'camera'],
      count: 1,
      sizeType: ['compressed'], // 图片尺寸，选项原图和压缩， h5端未实现压缩
    }).then(res => {
      let tempFiles = res.tempFiles[0]
      // 压缩图片
      // console.log(res)
      Taro.showLoading({ title: '图片上传中...' })
      this.imgCompressed(tempFiles.path, tempFiles.size, (blobFile) => {
        Taro.uploadFile({
          url: serverHost + uploadPath,
          filePath: blobFile,
          name: 'file',
          header: getToken()
        }).then(imgRes => {
          Taro.hideLoading()
          if(imgRes.statusCode != 200) { showToast('上传图片失败,错误原因: ' + imgRes.errMsg); return }
          // 图片正确上传
          let imgPath = JSON.parse(imgRes.data).result
          this.setState({ imgUpload: imgPath })
        }).catch(err1 => {
          Taro.hideLoading()
          console.error(err1)
          showToast('上传图片失败,请稍后重试~')
        })
      })
    }).catch(err => {
      console.error(err)
      showToast('打开图片失败,请稍后重试~')
    })
  }

  // 图片压缩
  imgCompressed = (imgPath: string, imgSize: number, callBack?) => {
    let quality = 1
    // 大于1M的压缩
    let sizeM = imgSize / 1024 / 1024
    console.log(sizeM)
    if(sizeM < 1 ) {
      // 不压缩
      quality = 1
      callBack(imgPath)
      return
    }
    else if(sizeM >= 1 && sizeM < 2) { quality = 0.95 }
    else if(sizeM >= 2 && sizeM < 3) { quality = 0.92 }
    else { quality = 0.8 }
    let image = document.createElement('img')
    image.crossOrigin = 'Anonymous'
    console.log(image)
    image.onload = function () {
      let canvas = document.createElement("canvas")
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext("2d")
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
      /**
       * 1、本来打算使用toBlob函数进行压缩，因为Taro的chooseImage函数返回的图片路径是blob类型的文件，可是toBlob函数不知道什么原因，并不能返回blob文件。于是打算转换成base64
       * 的图片，没想到也是可以上传的
       * 2、后来真机测试发觉想太多，在pc上能上传，但在手机上并不能上传，还是得转化成blob文件
       *
       */
      // 转化成blob文件
      // 第一个参数回调，第二个参数图片类型(image/png; image/jpeg)默认为image/png；第三个参数图片质量（0~1）取值
      canvas.toBlob((blobFile) => {
       // console.log(blobFile)
        // blob数据转化成url数据
        let url = URL.createObjectURL(blobFile)
        // console.log(url)
       callBack&&callBack(url)
      }, 'image/jpeg', quality)

      /*let dataUrl = canvas.toDataURL('image/jpeg', quality)
      if(!dataUrl) { showToast('图片上传压缩失败, 请重试！'); return }
      callBack&&callBack(dataUrl)*/
    }
    image.src = imgPath
  }

  // 图片预览
  imgPreView = (imgPath: any) => {
    let imgArr = imgPath
    if (typeof imgArr !== 'object'){ imgArr = [imgPath] }
    Taro.previewImage({
      urls: imgArr,
      current: '0'
    })
  }

  /**
   * @param imgField 图片字段名称
   */
  imgDelete(imgField: string) {
    this.setState({ [imgField]: '' })
    // 后期有删除接口的话待完善
  }

  render() {
    let { imgUpload } = this.state
    return (
      <View className='img-upload'>
        {
          imgUpload&&
          <View className='img-upload__btn'>
             <View className='img-upload__view' onClick={this.imgPreView.bind(this, imgUpload)} />
             <View className='img-upload__delete' onClick={this.imgDelete.bind(this, 'imgUpload')} />
          </View>
        }
          <View className='img-upload__con' onClick={this.imgUpload.bind(this)}>
            {
              imgUpload&&
              <Image src={imgUpload} className='img-upload__img' />
            }
          </View>
      </View>
    )
  }
}
